import axios from 'axios';
import {ElLoading, ElMessage} from 'element-plus';

// 创建一个 Axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL, // 基础 URL
	timeout: 1000000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		config.headers.Authorization = localStorage.getItem('aiToken') || '';
		// 显示加载中
		config.loadingInstance = ElLoading.service({
			lock: true,
			text: 'Loading...',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		if (process.env.NODE_ENV === "development") {
			config.url = `/api${config.url}`;
		} else {
			config.url = `https://api.visualx.art${config.url}`;
		}
		return config;
	},
	(error) => {
		// 请求错误处理
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		// 关闭加载中
		if (response.config.loadingInstance) {
			response.config.loadingInstance.close();
		}

		try {
			if (response.data.code === 4 ||response.data.code === 401) {
				ElMessage({ message: '登录状态失效，请重新登录', type: 'warning' });
				localStorage.removeItem('aiToken');
				localStorage.removeItem('email');
				// 怎么跳到登录页
				window.location.href='/login'
			} else {
				return response.data;
			}
		} catch (err) {
			return response.data;
		}
	},
	(error) => {
		// 关闭加载中
		if (error.config && error.config.loadingInstance) {
			error.config.loadingInstance.close();
		}
		return Promise.reject(error);
	}
);

// 封装请求方法
const request = async (url, method = 'GET', data = null, config = {}) => {
	try {
		return await service.request({
			url: url,
			method,
			data,
			...config,
		});
	} catch (error) {
		// 捕获请求错误
		console.error('Request error:', error.message);
		throw error;
	}
};

// 导出封装的请求方法
export const get = (url, config) => request(url, 'GET', null, config);
export const post = (url, data, config = {
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
		'locale': localStorage.getItem('locale') || 'zh'
	}
}) => request(url, 'POST', data, config);
export const put = (url, data, config) => request(url, 'PUT', data, config);
export const del = (url, config) => request(url, 'DELETE', null, config);
